package com.analysis.common;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.springframework.util.StringUtils;

public class PostConnection {

	private static final String SERVLET_POST = "POST";// 请求方式
	private static int Timeout = 600000;// 设置超时时间
	private boolean isTimeOut = false;// 是否超时

	public String doLoopPost(String urlStr) {
		String content = null;
		int times = 0;
		catchData:
		while(StringUtils.isEmpty(content)) {
			times++;
			if(times!=1) {
				try {
					Thread.sleep(1000*10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			content = doPost(urlStr);
            System.out.println("Try to catch Data [" + times + "/10].");
			if(times==10) {
				break catchData;
			}
		}
		return content;
	}
	
	/**
	 * 通过连接请求数据
	 *
	 * @param urlStr
	 * @return
	 */
	public String doPost(String urlStr) {
		isTimeOut = false;
		InputStream in = null;
		FileOutputStream out = null;
		HttpURLConnection conn = null;
		String result = "";
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();// 根据url获取连接
			// 设置请求参数
			conn.setDoInput(true);
			conn.setConnectTimeout(Timeout);
			conn.setReadTimeout(Timeout);
			conn.setUseCaches(false);
			conn.setRequestMethod(SERVLET_POST);
			conn.connect();// 连接
			in = conn.getInputStream();// 获取返回的数据流

			//解决编码问题，返回的数据为GBK，而eclipse工作环境为UTF-8
			//需要将获得的输入流使用GBK
			// 对返回的数据流转换成String数据类型并返回
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in,"GBK"));

//			BufferedReader reader = new BufferedReader(
//                    new InputStreamReader(in));
			StringBuffer sb = new StringBuffer();
			String str;
			while ((str = reader.readLine()) != null) {
				sb.append(str);
			}
			result = sb.toString();
		} catch (ConnectException e) {
			isTimeOut = true;
			e.printStackTrace();
		} catch (SocketTimeoutException e) {
			isTimeOut = true;
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 最后关闭所有的连接
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
				if (conn != null) {
					conn.disconnect();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public boolean isTimeOut() {
		return isTimeOut;
	}

	public void setTimeOut(boolean isTimeOut) {
		this.isTimeOut = isTimeOut;
	}
}